import asyncio
import requests
import websockets
import json
from base64 import b64decode
from zlib import decompress, MAX_WBITS

from urllib.parse import urlparse, urlunparse, urlencode


def get_ws_url(url = "https://socket-v3.bittrex.com/signalr", hub_name = 'c3'):
  negotiate_tpml = '/negotiate'
  # query_para = urlencode({
  #   'connectionData': '''[{"name": "c3"}]''',
  #   'clientProtocol': '1.5',
  # })
  token = requests.get(url + negotiate_tpml).json()['ConnectionToken']
  # query_para = urlencode({
  #   'transport': 'webSockets',
  #   'connectionToken': token,
  #   'connectionData': [{"name": hub_name}],
  #   'clientProtocol': '1.5',
  # })
  ws_url = f"wss://socket-v3.bittrex.com/signalr/connect?transport=webSockets&{urlencode({'connectionToken': token})}"
  print(ws_url)
  return ws_url


async def get_btc_ticker():
  ws_url = get_ws_url()
  async with websockets.connect(ws_url) as websocket:
    req = '''{"H":"c3","M":"Subscribe","A":[["trade_BTC-USDT","trade_ETH-USDT","trade_XRP-USDT"]],"I":1}'''
    await websocket.send(req)
    while True:
      data = json.loads((await websocket.recv()))
      print(data)
      msgs = data['M'] if 'M' in data and len(data['M']) > 0 else {}
      for msg in msgs: 
        if "M" in msg:
          print(msg["M"])
        if "A" in msg:
          for feed in msg["A"]:
            decompressed_msg = decompress(b64decode(feed, validate=True), -MAX_WBITS)
            print(decompressed_msg)

asyncio.run(get_btc_ticker())


